<script setup lang="ts">
import { ElMessage, InputInstance } from "element-plus";
import { ref, nextTick, watch } from "vue";
import router from "../config/route";
import { useRoute } from "vue-router";
import { defineProps } from "vue";
import { addQuestionUsingPost, getQuestionVoByIdAdminUsingGet, updateQuestionUsingPost } from "../servers/question/api/questionController";

// 初始化表单数据
const initFormData: API.QuestionAddRequest = {
  answer: "",
  content: "",
  judgeCase: [],
  judgeConfig: { memoryLimit: 1000, timeLimit: 1000, stackLimit: 1000 },
  tags: [],
  title: "",
};

// 表单数据
const formData = ref({ ...initFormData });

// 获取数据
const getQuestionById = async (id: number) => {
  const res = await getQuestionVoByIdAdminUsingGet({ id });
  // 获取成功
  if (res.data.code === 200) {
    console.log("获取修改数据id成功", res.data.data);
    // 填充表单
    formData.value = { ...res.data.data?.questionVO };
    formData.value.answer = res.data.data?.question?.answer;
  } else {
    ElMessage.error("获取修改题目失败");
    router.push("/meQuestion");
  }
};

// 通过props 获取题目id
const { id } = defineProps(["id"]);

// 判断路由
const route = useRoute();
const isAddStatus = ref(true);
if (route.name === "修改题目") {
  isAddStatus.value = false;
  // 获取需要修改的数据
  getQuestionById(id);
}

// 监听路由   预防添加转到修改 或者修改转到添加的路由修改方式
watch(()=>[route.name],([newValue])=>{
  console.log('路由修改了')
  if(newValue === '添加题目'){
  // 表单数据初始化
  formData.value = {...initFormData}
  }
})


// 标签方法
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref<InputInstance>();
const handleClose = (tag: string) => {
  formData.value.tags?.splice(formData.value.tags.indexOf(tag), 1);
};
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
const handleInputConfirm = () => {
  if (inputValue.value) {
    formData.value.tags?.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
// 添加测试用例
const addTestElement = () => {
  formData.value.judgeCase?.push({ input: "", output: "" });
};
// 删除测试用例
const deleteTestELement = (index: number) => {
  formData.value.judgeCase?.splice(index, 1);
};

// 提交
const onSubmit = async () => {
  // 进行判断 如果为添加，则添加
  if (isAddStatus.value) {
    // 发送请求 添加
    const res = await addQuestionUsingPost(formData.value);
    // 提交成功之后，跳转到题目显示页面
    if (res.data.code === 200) {
      ElMessage.success("题目提交成功");
      // 跳转
      router.push("/meQuestion");
    } else {
      ElMessage.error("题目提交失败" + res.data.message);
    }
  } else {
    // 若为修改，直接请求修改请求
    // 发送请求 添加
    const res = await updateQuestionUsingPost(formData.value);
    // 提交成功之后，跳转到题目显示页面
    if (res.data.code === 200) {
      ElMessage.success("题目修改成功");
      // 跳转
      router.push("/meQuestion");
    } else {
      ElMessage.error("题目修改失败" + res.data.message);
    }
  }
};
</script>

<template>
  <div
    class="add-or-update-queat-view"
    style="display: flex; justify-content: center"
  >
    <el-form
      ref="form"
      :model="formData"
      style="min-width: 800px"
      label-width="80px"
    >
      <el-form-item label="题目名称" prop="title">
        <el-input
          placeholder="请填写题目名称"
          :maxLength="20"
          v-model="formData.title"
        ></el-input>
      </el-form-item>
      <el-form-item label="题目描述" prop="content">
        <el-input
          placeholder="请填写题目描述"
          :maxLength="20"
          v-model="formData.content"
        ></el-input>
      </el-form-item>
      <el-form-item label="题目答案" prop="answer">
        <el-input
          placeholder="请填写题目答案"
          :maxLength="20"
          v-model="formData.answer"
        ></el-input>
      </el-form-item>

      <el-form-item label="题目标签" prop="tags">
        <!-- 标签 -->
        <el-tag
          v-for="tag in formData.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="InputRef"
          v-model="inputValue"
          class="w-20"
          size="small"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
          style="max-width: 64px"
        />
        <el-button
          v-else
          class="button-new-tag"
          size="small"
          @click="showInput"
        >
          + 添加标签
        </el-button>
      </el-form-item>

      <el-form-item label="测试用例" prop="judgeCase">
        <div>
          <el-button type="success" @click="addTestElement"> 添加</el-button
          ><br />
        </div>

        <div
          v-for="(item, index) in formData.judgeCase"
          style="max-width: 100px"
        >
          <div style="margin-left: 20px">
            输入用例{{ index + 1
            }}<el-input
              placeholder="请输入输入用例"
              v-model="item.input"
            ></el-input>
            输出用例{{ index + 1
            }}<el-input
              placeholder="请输入输入用例"
              v-model="item.output"
            ></el-input>
            <el-button
              type="danger"
              size="small"
              style="margin-top: 10px; display: flex; justify-self: center"
              @click="deleteTestELement(index)"
              >×</el-button
            >
          </div>
        </div>
      </el-form-item>

      <el-form-item label="题目配置" prop="judgeConfig">
        <div>
          内存占用：<el-input-number
            v-model="formData.judgeConfig!.memoryLimit"
            :min="0"
            style="margin: 0 5px"
          />
          时间占用：<el-input-number
            v-model="formData.judgeConfig!.timeLimit"
            :min="0"
            style="margin: 0 5px"
          />
          堆栈占用：<el-input-number
            v-model="formData.judgeConfig!.stackLimit"
            :min="0"
            style="margin: 0 5px"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button
          v-show="!isAddStatus"
          type="info"
          @click="router.push('/meQuestion')"
          >取消</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped></style>
